package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.MsgResult;
import com.itheima.common.R;
import com.itheima.dao.SysUserDao;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.SysUser;
import com.itheima.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserDao,SysUser> implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public R login(LoginDto loginDto,String code) {
        //1.判断下参数是否合法
        if (loginDto==null){
            log.info("密码不能为空");
            return new R(1, MsgResult.NULLPOINT,null);
        }
        //2.根据用户名查询用户对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,loginDto.getUserName());
        SysUser user = sysUserDao.selectOne(wrapper);
        if (user==null){
            log.info("账号错误");
            return new R(0,MsgResult.FAIL_LOGIN,null);
        }
        //3.加密密码
        String pwd = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //4.使用加密后的密码和数据库的密码进行匹配校验
        if (!user.getPassword().equals(pwd)){
            log.info("密码错误");
            return new R(0,MsgResult.FAIL_LOGIN,null);
        }
        //判断用户输入的验证码是否正确
        if (!code.equals(loginDto.getCode())){
            log.info("验证码错误");
            return new R(0,MsgResult.WRONG_VERIFICATION,null);
        }
        log.info("登陆成功");
        return new R(1,MsgResult.SUCCESS_LOGIN,user);
    }
}
